package com.atguigu.srb.core.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.atguigu.srb.core.pojo.entity.Dict;
import com.atguigu.srb.core.pojo.entity.vo.DictVO;
import com.atguigu.srb.core.service.DictService;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * ClassName: ExcelDictVoListener
 * Package: com.atguigu.srb.core.listener
 * Description:
 *
 * @Author 王晓龙
 * @Create 2023/3/28 9:58
 * @Version 1.0
 */
public class DictVoListener extends AnalysisEventListener<DictVO> {
    private DictService dictService;

    public DictVoListener(DictService dictService) {
        this.dictService = dictService;
    }


    //每隔五条保存一次
    private static final Integer LIMIT = 5;
    List<DictVO> dictVOList = new ArrayList<>();


    @Override
    public void invoke(DictVO dictVo, AnalysisContext analysisContext) {
        dictVOList.add(dictVo);
        if (dictVOList.size()==LIMIT){
            List<Dict> dictList = getDicts();
            //存入数据库
            dictService.saveBatch(dictList);
            dictVOList.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        if (dictVOList.size()>0){
            List<Dict> dictList = getDicts();
            //保存到数据库
            dictService.saveBatch(dictList);
            dictVOList.clear();
        }
    }

    private List<Dict> getDicts() {
        //将vo列表转换成dict列表
        List<Dict> dictList = dictVOList.stream().map(dictvo -> {
            Dict dict = new Dict();
            BeanUtils.copyProperties(dictvo, dict);
            return dict;
        }).filter(dict -> {
            return dictService.count(Wrappers.lambdaQuery(Dict.class)
                    .eq(Dict::getId, dict.getId()))==0;
        }).collect(Collectors.toList());
        return dictList;
    }
}